package com.twu.bean;

import static com.google.common.collect.Iterators.filter;
import static com.google.common.collect.Lists.newArrayList;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import com.google.common.base.Predicate;
import com.google.common.collect.UnmodifiableIterator;
import com.sun.istack.internal.Nullable;

public class UserList
{
	private static List<User> userList;

	public static User currentUser = null;

	static
	{
		userList = new ArrayList<User>();
		User user = new User("111-1111", "123");
		user.setInfo("paul", "paul@gmail.com", "123456789");
		userList.add(user);

		user = new User("111-1112", "234");
		user.setInfo("james", "james@gmail.com", "123456789");
		userList.add(user);

		user = new User("111-1113", "345");
		user.setInfo("george", "george@gmail.com", "123456787");
		userList.add(user);

		user = new User("111-1114", "456");
		user.setInfo("angela", "angela@gmail.com", "123456786");
		userList.add(user);

		user = new User("111-1115", "678");
		user.setInfo("daisy", "daisy@gmail.com", "123456785");
		userList.add(user);
	}

	private static String NAME_PATTERN = "[1-9]{3}-[1-9]{4}";

	public boolean isValid(User user)
	{
		return isFormatCorrect(user) && isMatch(user);
	}

	public User getCurrentUser()
	{
		return currentUser;
	}

	private boolean isFormatCorrect(User user)
	{
		return Pattern.compile(NAME_PATTERN).matcher(user.getUsername()).matches();
	}

	private boolean isMatch(User user)
	{
		UnmodifiableIterator<User> matchedUsers = filter(userList.iterator(), equals(user));
		ArrayList<User> users = newArrayList(matchedUsers);
		if (!users.isEmpty())
		{
			setCurrentUser(users);
			return true;
		}
		return false;
	}

	private void setCurrentUser(ArrayList<User> users)
	{
		currentUser = users.get(0);
	}

	private Predicate<User> equals(final User target)
	{
		return new Predicate<User>()
		{
			@Override
			public boolean apply(@Nullable User user)
			{
				return user.getUsername().equals(target.getUsername())
						&& user.getPassword().equals(target.getPassword());
			}
		};
	}
}
